const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlPlugin = require("html-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
const CompressionPlugin = require("compression-webpack-plugin");

module.exports = (env, argv) => {
  const isProduction = argv.mode === "production";
  
  return {
    entry: "./src/index.jsx",
    mode: isProduction ? "production" : "development",
    devtool: isProduction ? false : "source-map",
    output: {
      path: path.resolve(__dirname, "dist"),
      filename: "[name].[contenthash].js",
      assetModuleFilename: "assets/[name].[hash][ext]",
      publicPath: "/"
    },
    resolve: {
      extensions: [".js", ".jsx", ".less"]
    },
    optimization: {
      minimize: isProduction,
      minimizer: [
        new TerserPlugin({
          terserOptions: {
            compress: {
              drop_console: isProduction,
              drop_debugger: isProduction,
              pure_funcs: isProduction ? ['console.log'] : [],
            },
            mangle: true,
          },
          extractComments: false,
        }),
        new CssMinimizerPlugin(),
      ],
      splitChunks: {
        chunks: 'all',
        maxInitialRequests: Infinity,
        minSize: 20000,
        cacheGroups: {
          vendors: {
            test: /[\\/]node_modules[\\/]/,
            priority: -10,
            name(module) {
              // 获取包名
              const packagePath = module.context || '';
              // 安全地获取包名
              const match = packagePath.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/);
              const packageName = match ? match[1] : 'vendors';
              
              // 针对特定大型包单独分割
              if (/xlsx/.test(packageName)) return 'xlsx';
              if (/quill/.test(packageName)) return 'quill';
              if (/echarts/.test(packageName)) return 'echarts';
              if (/antd/.test(packageName)) return 'antd';
              if (/moment/.test(packageName)) return 'moment';
              if (/react|redux/.test(packageName)) return 'react-base';

              // 其他依赖分到vendors中
              return 'vendors';
            }
          },
        }
      },
      runtimeChunk: 'single',
    },
    plugins: [
      new CleanWebpackPlugin(),
      new MiniCssExtractPlugin({
        filename: isProduction ? "[name].[contenthash].css" : "[name].css",
        chunkFilename: isProduction ? "[id].[contenthash].css" : "[id].css"
      }),
      new HtmlPlugin({
        template: "./public/index.html",
        filename: "index.html",
        minify: isProduction ? {
          removeComments: true,
          collapseWhitespace: true,
          removeRedundantAttributes: true,
          useShortDoctype: true,
          removeEmptyAttributes: true,
          removeStyleLinkTypeAttributes: true,
          keepClosingSlash: true,
          minifyJS: true,
          minifyCSS: true,
          minifyURLs: true,
        } : false
      }),
      ...(isProduction ? [
        new CompressionPlugin({
          algorithm: 'gzip',
          test: /\.(js|css|html|svg)$/,
          threshold: 10240,
          minRatio: 0.8,
        }),
      ] : []),
      ...(process.env.ANALYZE ? [new BundleAnalyzerPlugin()] : [])
    ],
    devServer: {
      open: true,
      host: "127.0.0.1",
      port: 8089,
      historyApiFallback: true,
      static: {
        directory: path.join(__dirname, "public"),
        serveIndex: false
      },
      proxy: [
        {
          context: ['/api', '/uploads'],
          target: 'http://localhost:3000',
          changeOrigin: true,
          logLevel: 'debug',
          onProxyReq(proxyReq, req, res) {
            console.log('代理请求:', req.method, req.url);
          },
          onProxyRes(proxyRes, req, res) {
            console.log('代理响应:', proxyRes.statusCode);
          }
        }
      ],
      devMiddleware: {
        writeToDisk: true
      },
      hot: true,
      client: {
        overlay: {
          errors: true,
          warnings: false
        }
      }
    },
    module: {
      rules: [
        {
          test: /\.(js|jsx)$/i,
          exclude: /node_modules/,
          use: "babel-loader"
        },
        {
          test: /\.less$/i,
          use: [
            MiniCssExtractPlugin.loader,
            {
              loader: "css-loader",
              options: {
                sourceMap: !isProduction,
                importLoaders: 2,
                modules: {
                  auto: true,
                  localIdentName: isProduction ? '[hash:base64]' : '[path][name]__[local]'
                }
              }
            },
            {
              loader: "less-loader",
              options: {
                sourceMap: !isProduction,
                lessOptions: {
                  javascriptEnabled: true
                }
              }
            }
          ]
        },
        {
          test: /\.css$/i,
          use: [
            MiniCssExtractPlugin.loader,
            {
              loader: "css-loader",
              options: {
                sourceMap: !isProduction,
                importLoaders: 1
              }
            }
          ]
        },
        {
          test: /\.(png|jpg|gif|svg)$/i,
          type: "asset",
          parser: {
            dataUrlCondition: {
              maxSize: 4096  // 更小的图片才内联
            }
          }
        },
        {
          test: /\.ico$/,
          type: "asset/resource",
          generator: {
            filename: "assets/icons/[name][ext]"
          }
        }
      ]
    }
  };
};
